﻿$(document).ready(function () {

    if (localStorage.rowlength) { $("#select_row").val(localStorage.rowlength); } else { localStorage.rowlength = 10; }

    $('#reload').click(function () {
        var Array_title = new Array("分类标题", "时间", "处理");
        var Array_id = new Array("id", "classname", "time");
        page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", '15', '4', Array_title, 'galleryclass');
    });


    var Array_title = new Array("分类标题", "时间", "处理");
    var Array_id = new Array("id", "classname", "time");
    page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", '15', '4', Array_title, 'galleryclass');


    $("#deletebtn").click(function () {
        deleteAll('newsclass');
    });
});


function changerow(container, row, column) {
    if (localStorage.rowlength) { localStorage.rowlength = row; } else { $("#select_row").val("10"); localStorage.rowlength = "10"; }

    if (column == "divtable1") {
        var Array_title = new Array("分类标题", "时间", "处理");
        var Array_id = new Array("classid", "classname", "time");
        page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", row, '4', Array_title, 'galleryclass');
    }
    else {
        //另外样式
        var Array_title = new Array("分类标题", "时间", "处理");
        var Array_id = new Array("classid", "classname", "time");
        page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, "main", row, '4', Array_title, 'galleryclass');
    }
}





var dialogID, rowCount;  // dialogID窗口id  rowCount 数据库记录数
//（_page_url,page_url)分页处理地址 (_get_url , get_url)获取数据地址 （_Array_id,Array_id）数据表字段id   
//(_container,container) 容器id   (_row,row)行   (_column,column)列  (_Array_title,Array_title)表头标题  
//(_table,table)修改的表名  (curr_num,num)当前页   datacount纪录总数
var _page_url, _get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num = 1, datacount = 0;
//获取数据
//url 处理地址   Array_id数据表id    container 容器id   row行    column列  Array_title表头标题  table修改的表名  num当前页
function get(url, Array_id, container, row, column, Array_title, table, num) {
    var tmp = Math.random().toString();
    var select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : 10;
    var sql;
    if (num == 1) {
        sql = "select * from " + table + " order by time DESC" + " limit 0," + num * select_row;
    }
    else { sql = "select * from " + table + " order by time DESC" + " limit " + (num - 1) * select_row + "," + select_row; }
    //var test = { user_name: "objVal['user_name']", user_pwd: "objVal['user_pwd]", add_time: "objVal['add_time']" }
    //test["user_name"]; 常量
    $.ajax({
        type: 'POST',
        url: url + tmp,
        data: "sql=" + sql + "&curr=" + num,
        dataType: 'json',
        cache: false,
        beforeSend: function () {
            dialogID = layer.load(2, { shade: [0.1, '#fff'] });
        },
        success: function (data, textStatus) {
            layer.close(dialogID);
            var jsonData = eval(data);
            var Array_item = [];
            rowCount = jsonData.length;
            create(container, row, column, Array_title, table);
            //$("#delete").attr("Dataid", Array_id[0])
            $.each(jsonData, function (index, objVal) { //遍历对象数组，index是数组的索引号，objVal是遍历的一个对象。objVal["属性"]可取到对应的属性值。 
                //方法1
                //Array_item = [objVal["user_id"], objVal["user_name"], objVal["user_pwd"], objVal["add_time"]];
                //方法2

                $.each(Array_id, function (idx, val) {
                    Array_item.push(objVal[val]);
                });
                var row_count = $("#cont tr").length;

                var column_count = $("#r-" + index + " td").length;

                $("#checkall").attr("Dataid", Array_id[0]);//主键
                var m = 0;
                //列 
                for (m; m < column_count; m++) {
                    if (m == 0) {
                        $("#del-" + index).attr("Datavalue", Array_item[0]);//主键
                        $("#del-" + index).attr("Dataid", Array_id[0]);//主键
                    } else {
                        if (m >= column_count) {
                            $("#r-" + index + "-" + m).attr("Datavalue", Array_item[0]);//主键
                            $("#r-" + index + "-" + m).attr("Dataid", Array_id[0]);//主键ID
                        }
                        else {

                            $("#r-" + index + "-" + m).html(Array_item[m]);
                            $("#r-" + index + "-" + m).attr("Dataid", Array_id[m]);
                        }
                    }
                }
                Array_item = [];
            });


        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return;
            }
            layer.close(dialogID);
            layer.msg('加载失败', { icon: 1, time: 2000 });
            return;
        },

    });
}



//绘制表格
//container 容器id   row行    column列  Array_title表头标题  table修改的表名
function create(container, row, column, Array_title, table) {
    var _row = row;
    $("#" + container).empty();
    var c = 0;
    $("#" + container).append('<table id="tab" data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" data-pagination="true" data-sort-name="name" data-sort-order="desc" class="table table-hover table-striped"></table>')
    $("#tab").append("<thead id='title'></thead>")
    $("#title").append("<tr id='line' class='sui-alt-row sui-selected'></tr>");
    for (c; c < column; c++) {
        if (c == 0) { $("#line").append("<th class=li" + c + "><div class='th-inner'><input type='checkbox' id='checkall'/></div></th>"); }
        else { $("#line").append("<th class=li" + c + "><div class='th-inner'>" + Array_title[c - 1] + "</div><div class='fht-cell'></div></th>"); }
    }
    $("#tab").append("<tbody id='cont'></tbody")

    var i = 0;
    original_row = -1;//纪录点击的行 -1 为归位。
    if (rowCount < row) { row = rowCount; } else if (rowCount > row || row > _row) { row = _row; }
    //console.log(row);
    for (i; i < row; i++) {
        $("#cont").append("<tr id=r-" + i + "></tr>");
        var j = 0;
        for (j; j < column; j++) {
            if (j == 0) {
                $("#r-" + i).append("<td id=r-" + i + "-" + j + "><input type='checkbox' id=del-" + i + " /></td>");
            }
            else {
                if (j == (column - 1)) {

                    $("#r-" + i).append("<td><a id='r-" + i + "-" + j + "' href='#' onclick=button_state('r-" + i + "-" + j + "','r-" + i + "-" + (j + 1) + "','r-" + i + "-" + (j + 2) + "','r-" + i + "-" + (j + 3) + "','" + i + "','" + j + "','edit'); class=li" + (j + 1) + ">" + "编辑" + "</a>&nbsp;"
                    + "<a id='r-" + i + "-" + (j + 1) + "' href='#' onclick=button_state('r-" + i + "-" + j + "','r-" + i + "-" + (j + 1) + "','r-" + i + "-" + (j + 2) + "','r-" + i + "-" + (j + 3) + "','" + i + "','" + j + "','update','" + table + "');  class='li" + (j + 1) + "' style='display:none;'>" + "更新" + "</a>&nbsp;"
                    + "<a id='r-" + i + "-" + (j + 2) + "'  href='#' onclick=button_state('r-" + i + "-" + j + "','r-" + i + "-" + (j + 1) + "','r-" + i + "-" + (j + 2) + "','r-" + i + "-" + (j + 3) + "','" + i + "','" + j + "','cancel');  class='li" + (j + 1) + "' style='display:none;'>" + "取消" + "</a>&nbsp;"
                    + "<a id='r-" + i + "-" + (j + 3) + "'href='#' onclick=button_state('r-" + i + "-" + j + "','r-" + i + "-" + (j + 1) + "','r-" + i + "-" + (j + 2) + "','r-" + i + "-" + (j + 3) + "','" + i + "','" + j + "','delete','" + table + "'); class=li" + (j + 1) + ">" + "删除" + "</a>&nbsp;"
                    + "<a id='r-" + i + "-" + (j + 4) + "'href='#' onclick='' class=li" + (j + 1) + ">" + "生成" + "</a></td>");
                }
                else {
                    $("#r-" + i).append("<td id='r-" + i + "-" + j + "' class=li" + j + ">" + "&nbsp;" + "</td>")
                }
            }
        }
    }
    $("#itemContainer li").hover(
                   function () { $(this).addClass("hover"); },
                   function () { $(this).removeClass("hover"); }
     );
    $("#checkall").click(function () {
        for (var i = 0; i < $("#cont tr").length; i++) {

            if ($("#checkall").is(":checked")) {
                $("#del-" + i).prop("checked", true);  //全选
            }
            else {
                $("#del-" + i).prop("checked", false); //取消全选 
            }
        }
    });
}



//数据库操作
function execute(sql) {
    return $.ajax({                                                  //调用jquery的ajax方法   
        type: "POST",                                      //设置ajax方法提交数据的形式   
        url: "handler/ExecuteHandler.ashx",                                       //把数据提交到ashx  
        data: "sql=" + sql,     //输入框writer中的值作为提交的数据 
        beforeSend: function () {

        },
        success: function (msg) {                  //提交成功后的回调，msg变量是输出的内容。      
            //如果有必要，可以把msg变量的值显示到某个DIV元素中 
            layer.msg('处理成功', { icon: 1, time: 2000 });
            JsonData = {};
            $("#addbtn").attr('value', "添加");
            $("#addbtn").removeAttr("disabled");
            return true;
        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return false;
            }
            layer.msg('处理失败', { icon: 2, time: 2000 });
            return false;
        },
    });
}



//添加或者修改json数据  row 当前行id   name  json属性  value json值
//var employees = [
//{ "firstName": "Bill", "lastName": "Gates" },
//{ "firstName": "George", "lastName": "Bush" },
//{ "firstName": "Thomas", "lastName": "Carter" }
//];
var JsonData = {}, singleA = 0;
function setJson(row, name, value) {
    if (singleA != row && singleA > 0) {
        // 添加 或 修改
        JsonData = {};
        JsonData[name] = value;
        singleA = row;
    }
    else {
        // 添加 或 修改
        JsonData[name] = value;
        singleA = row;
    }
    console.log(JsonData);
}

//按钮状态   edit_button 编辑按钮 update_button 更新按钮 cancel_button 取消按钮 del_button 删除按钮 row 当前行 column 当前列 type 当前按钮类型
var original_row = -1;  //-1为第一点击 //纪录点击的行 -1 为归位。
function button_state(edit_button, update_button, cancel_button, del_button, row, column, type, tableid) {
    var row_count = $("#cont tr").length;
    var a = 1, b = 1, c = 1, r = 0;
    switch (type) {
        case "edit":
            if (document.getElementById("r-" + row + "-1").innerHTML != "&nbsp;") {//数据是否为空

                $("#" + edit_button + "").css("display", "none");
                $("#" + del_button + "").css("display", "none");
                $("#" + update_button + "").css("display", "");
                $("#" + cancel_button + "").css("display", "");
                for (c; c < column; c++) {
                    if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                        var value = $("#r-" + row + "-" + c + "").html();
                        $("#r-" + row + "-" + c + "").empty();
                        $("#r-" + row + "-" + c + "").attr("Datavalue", value);
                        $("#r-" + row + "-" + c + "").append("<input type='text' onchange=setJson('" + row + "','" + $("#r-" + row + "-" + c + "").attr("Dataid") + "',this.value) style='width:90%;' value='" + $("#r-" + row + "-" + c + "").attr("Datavalue") + "'/>");
                    } else { break; }
                }

                if (original_row != row) {
                    for (a; a < column; a++) {
                        if (a != row) {
                            $("#r-" + original_row + "-" + column + "").css("display", "");
                            $("#r-" + original_row + "-" + (Number(column) + 1) + "").css("display", "none");
                            $("#r-" + original_row + "-" + (Number(column) + 2) + "").css("display", "none");
                            $("#r-" + original_row + "-" + (Number(column) + 3) + "").css("display", "");
                        }
                    }
                    for (b; b < column; b++) {
                        if ($("#r-" + row + "-" + b + "").attr("Dataid") != "time") {//时间字段不需要编辑
                            $("#r-" + original_row + "-" + b + "").empty();
                            $("#r-" + original_row + "-" + b + "").append($("#r-" + original_row + "-" + b + "").attr("Datavalue"));
                        } else { break; }
                    }
                    //纪录当前行
                    original_row = row;
                }
            }
            else { layer.msg('无数据', { icon: 2, time: 2000 }); }
            break;
        case "cancel":

            for (r; r < row_count; r++) {
                $("#r-" + r + "-" + column + "").css("display", "");
                $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
            }
            for (c; c < column; c++) {
                if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                    $("#r-" + row + "-" + c + "").empty();
                    $("#r-" + row + "-" + c + "").append($("#r-" + row + "-" + c + "").attr("Datavalue"));
                } else { break; }
            }
            break;
        case "update":
            //数据库操作
            var sqlstring = null;
            $.each(JsonData, function (idx, val) {//迭代jsondate 为空不执行。
                sqlstring = "UPDATE " + tableid + " SET";
                $.each(JsonData, function (name, value) {
                    sqlstring = sqlstring + " " + name + "='" + value + "',";
                });
            });
            if (sqlstring != null) {
                console.log("#r-" + row + "-" + column);
                sqlstring = sqlstring.substring(0, sqlstring.length - 1) + " WHERE " + $("#del-" + row).attr("Dataid") + " ='" + $("#del-" + row).attr("Datavalue") + "'";
                if (execute(sqlstring)) {
                    $("#" + edit_button + "").css("display", "");
                    $("#" + del_button + "").css("display", "");
                    $("#" + update_button + "").css("display", "none");
                    $("#" + cancel_button + "").css("display", "none");
                    for (r; r < row_count; r++) {
                        $("#r-" + r + "-" + column + "").css("display", "");
                        $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                        $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                        $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                    }
                    for (c; c < column; c++) {
                        if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                            var value = $("#r-" + row + "-" + c + " input").val();
                            $("#r-" + row + "-" + c).attr("Datavalue", value);
                            $("#r-" + row + "-" + c + " input").remove();
                            $("#r-" + row + "-" + c + "").append(value);
                        } else { break; }
                    }
                }
            }
            else {
                $("#" + edit_button + "").css("display", "");
                $("#" + del_button + "").css("display", "");
                $("#" + update_button + "").css("display", "none");
                $("#" + cancel_button + "").css("display", "none");
                for (r; r < row_count; r++) {
                    $("#r-" + r + "-" + column + "").css("display", "");
                    $("#r-" + r + "-" + (Number(column) + 1) + "").css("display", "none");
                    $("#r-" + r + "-" + (Number(column) + 2) + "").css("display", "none");
                    $("#r-" + r + "-" + (Number(column) + 3) + "").css("display", "");
                }
                for (c; c < column; c++) {
                    if ($("#r-" + row + "-" + c + "").attr("Dataid") != "time") {//时间字段不需要编辑
                        var value = $("#r-" + row + "-" + c + " input").val();
                        $("#r-" + row + "-" + c).attr("Datavalue", value);
                        $("#r-" + row + "-" + c + " input").remove();
                        $("#r-" + row + "-" + c + "").append(value);
                    } else { break; }
                }
                layer.msg('数据没有变动', { icon: 4, time: 2000 });
            }
            break;
        case "delete":
            if (document.getElementById("r-" + row + "-1").innerHTML != "&nbsp;") {//数据是否为空
                //询问框
                layer.confirm('您是否要删除？', {
                    btn: ['是的', '算了'] //按钮
                }, function () {
                    var sqlstring = "delete from " + tableid + " WHERE " + $("#del-" + row).attr("Dataid") + " ='" + $("#del-" + row).attr("Datavalue") + "'";

                    if (execute(sqlstring)) {
                        $("#r-" + row).remove();
                        row_count = $("#cont tr").length;

                        //单独删除数据后 如果执行分页
                        if (row_count == 0) {
                            curr_num = (parseInt(curr_num) - 1) <= 0 ? 1 : (parseInt(curr_num) - 1);
                            deleteCount = deleteCount + 1;
                            var current = Math.ceil((parseInt(datacount) - parseInt(deleteCount)) / $("#select_row").val()) == 0 ? 1 : Math.ceil((parseInt(datacount) - parseInt(deleteCount)) / $("#select_row").val());
                            console.log("***" + current);
                            $.jqPaginator('.pagination', {
                                totalPages: parseInt(current),
                                visiblePages: parseInt($("#select_row").val()),
                                //currentPage: parseInt(curr_num) - 1 == 0 ? curr_num = 1 : parseInt(curr_num) - 1,
                                currentPage: curr_num,
                                onPageChange: function (num, type) {
                                    curr_num = num;
                                    //page("handler/PageHandler.ashx?t=", "handler/GetHandler.ashx?t=", Array_id, container, row, column, Array_title, table);
                                    get(_get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num);
                                }
                            });
                        }
                    };
                    if (original_row != row) {
                        for (a; a < column; a++) {
                            if (r != row) {
                                $("#r-" + original_row + "-" + column + "").css("display", "");
                                $("#r-" + original_row + "-" + (Number(column) + 1) + "").css("display", "none");
                                $("#r-" + original_row + "-" + (Number(column) + 2) + "").css("display", "none");
                                $("#r-" + original_row + "-" + (Number(column) + 3) + "").css("display", "");
                            }
                        }
                        for (b; b < column; b++) {
                            $("#r-" + original_row + "-" + b + "").empty();
                            $("#r-" + original_row + "-" + b + "").append($("#r-" + original_row + "-" + b + "").attr("Datavalue"));
                        }
                    }

                }, function () {
                    //layer.msg('取消', {
                    //    time: 20000, //20s后自动关闭
                    //    btn: ['明白了', '知道了']
                    //});
                });
            } else { layer.msg('无数据', { icon: 2, time: 2000 }); }
            break;
        default:
            //type 与 case 1 和 case 2 不同时执行的代码
    }

}

//全部删除  deleteCount 统计删除数据的记录个数   
var deleteCount = 0;
function deleteAll(tableid) {
    var li = 0, deleteID = null, licount, rowid = [];
    licount = $("#cont tr").length;
    for (li; li < licount; li++) {
        if ($("#del-" + li).is(":checked")) {
            rowid.push("#r-" + li);
            deleteCount = deleteCount + 1;
            if (deleteID == null) { deleteID = "'" + $("#del-" + li).attr("datavalue") + "'"; }
            else { deleteID = deleteID + ",'" + $("#del-" + li).attr("datavalue") + "'"; }
        } else { continue; }
    }
    if (deleteID != null) {
        layer.confirm('您是否要删除？', {
            btn: ['是的', '算了'] //按钮
        }, function () {
            var sqlstring = "delete from " + tableid + " where " + $("#checkall").attr("Dataid") + " in(" + deleteID + ");"
            if (execute(sqlstring)) {
                for (var i = 0; i < rowid.length; i++) {
                    $(rowid[i]).remove();
                }
                rowid = [];
                var row_count = $("#cont tr").length;
                if (row_count == 0) {
                    curr_num = parseInt(curr_num) - 1;
                    deleteCount = deleteCount + rowid.length;
                    var current = Math.ceil((parseInt(datacount) - parseInt(deleteCount)) / $("#select_row").val());
                    $.jqPaginator('.pagination', {
                        totalPages: parseInt(current),
                        visiblePages: parseInt($("#select_row").val()),
                        //currentPage: parseInt(curr_num) - 1 == 0 ? curr_num = 1 : parseInt(curr_num) - 1,
                        currentPage: curr_num,
                        onPageChange: function (num, type) {
                            curr_num = num;
                            get(_get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num);
                        }
                    });
                }

            }
        }, function () {
            //layer.msg('取消', {
            //    time: 20000, //20s后自动关闭
            //    btn: ['明白了', '知道了']
            //});
        });

    } else { layer.msg('请先选择要删除的数据！', { icon: 2, time: 2000 }); };
}


// pagecount num当前页  curr_num全局变量 存储当前页    datacount纪录总数
//第一次加载分页
function page(page_url, get_url, Array_id, container, row, column, Array_title, table, func) {
    var tmp = Math.random().toString();
    var sql = "select count(*) from " + table;
    $.ajax({
        type: 'POST',
        url: page_url + tmp,
        data: "sql=" + sql,
        dataType: 'text',
        cache: false,
        beforeSend: function () {
            dialogID = layer.load(2, { shade: [0.1, '#fff'] });
        },
        success: function (data, textStatus) {
            //layer.close(dialogID);
            console.log(data);
            datacount = parseInt(data) == 0 ? data = 1 : data;
            var select_row = parseInt($("#select_row").val()) ? parseInt($("#select_row").val()) : 10;
            var current = Math.ceil(parseInt(datacount) / select_row);
            console.log(current);
            $.jqPaginator('.pagination', {
                totalPages: parseInt(current),
                visiblePages: select_row,
                currentPage: 1,
                onPageChange: function (num, type) {
                    curr_num = num;  //(curr_num,num)当前页              
                    _page_url = page_url;//（_page_url,page_url)分页处理地址
                    _get_url = get_url;//(_get_url , get_url)获取数据地址
                    _Array_id = Array_id;//（_Array_id,Array_id）数据表字段id 
                    _container = container;//(_container,container) 容器id
                    _row = row;// (_row,row)行
                    _column = column;// (_column,column)列
                    _table = table;//(_table,table)修改的表名
                    _Array_title = Array_title;//(_Array_title,Array_title)表头标题
                    console.log(type + '---' + curr_num);
                    get(_get_url, _Array_id, _container, _row, _column, _Array_title, _table, curr_num, func);
                }
            });

        },
        error: function (xhr) {
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { // 兼容调试时301/302重定向导致触发error的问题
                console.log(xhr);
                this.success(eval('(' + xhr.responseText + ')'), xhr.statusText);
                return;
            }
            layer.close(dialogID);
            layer.msg('加载失败', { icon: 1, time: 2000 });
            return;
        },

    });
}



